package club.hicode.daydayup.netty.udp.client;

import club.hicode.daydayup.netty.udp.MessageBo;
import cn.hutool.json.JSONUtil;
import com.github.sd4324530.jtuple.Tuple2;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 关于Agent代理的测试
 *
 * @author Liu Chunfu
 * @date 2018-07-09 上午11:37
 **/
public class AgentHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    public static final Map<String, MessageBo> map = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        String body = packet.content().toString(CharsetUtil.UTF_8);
        System.out.println("客户端收到消息:" + body);
        MessageBo messageBo = JSONUtil.toBean(body, MessageBo.class);
        String id = messageBo.getId();
        map.put(id, messageBo);
        Tuple2<Lock, Condition> tuple2 = KV.get(id);
        System.out.println("id为：" + id + "：结果: " + tuple2);
        if (tuple2 == null) {
            return;
        }
        Lock lock = tuple2.first;
        Condition condition = tuple2.second;
        try {
            lock.lock();
            condition.signal();
            System.out.println("客户端收到的消息：" + body);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
